package com.springboot.demo.config;

import java.util.List;
import org.springframework.boot.env.YamlPropertySourceLoader;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.Resource;

/**
 * yaml文件上下文初始化
 *
 * @author supu
 * @create 2018-12-18 14:13
 **/
public class YamlFileApplicationContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
    @Override
    public void initialize(ConfigurableApplicationContext applicationContext) {
        try {
            Resource[] resources = applicationContext.getResources("classpath:config/*.yml");
            YamlPropertySourceLoader sourceLoader = new YamlPropertySourceLoader();
            for(int i = 0; i < resources.length; i++) {
                List<PropertySource<?>> yamlFiles = sourceLoader.load(resources[i].getFilename(), resources[i]);
                applicationContext.getEnvironment().getPropertySources().addFirst(yamlFiles.get(0));
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
